package com.fita.admin.service.report.impl;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.fita.admin.dao.PrincipalDao;
import com.fita.admin.dao.UserWalletDao;
import com.fita.admin.service.DataServiceImpl;
import com.fita.admin.service.report.RechargeRecordService;
import com.fita.entity.principal.Principal;
import com.fita.entity.wallet.RechargeRecord;
import com.fita.entity.wallet.TransactionRecord;
import com.fita.entity.wallet.UserWallet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: 11200
 * @date: 2019/7/26
 */
@Service("rechargeRecordService")
public class RechargeRecordServiceImpl extends DataServiceImpl<RechargeRecord> implements RechargeRecordService {

    @Dao
    private UserWalletDao userWalletDao;

    @Dao
    private PrincipalDao principalDao;

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /**
     * recharge offline
     *
     * @param rechargeRecord
     * @param targetAgentCompanyId
     * @param loginId
     */
    public void offlineRecharge(RechargeRecord rechargeRecord, Long targetAgentCompanyId, Long loginId) {

        boolean validate = this.validate(rechargeRecord);

        if (!validate) {
            throw new BusinessException("验证失败");
        }

        Integer amount = rechargeRecord.getAmount();

        amount = amount * 100;

        Principal principal = genericDaoSupport.load(Principal.class, loginId);

        UserWallet userWallet = userWalletDao.loadByAgentCompanyId(targetAgentCompanyId);

        // 创建充值记录
        RechargeRecord newRechargeReocrd = new RechargeRecord(userWallet, amount);

        // 钱包充值
        userWallet.recharge(newRechargeReocrd);
        genericDaoSupport.update(userWallet);

        // 线下充值
        newRechargeReocrd.offlineRechargePaid(amount, rechargeRecord.getPayType(), rechargeRecord.getPayCode(), principal, userWallet.getTotalAmount());
        genericDaoSupport.save(newRechargeReocrd);

        // 创建记录
        TransactionRecord transactionRecord = new TransactionRecord(newRechargeReocrd, userWallet);
        genericDaoSupport.save(transactionRecord);
    }

    /**
     * 线下充值表单校验
     * @param rechargeRecord
     * @return
     */
    private boolean validate(RechargeRecord rechargeRecord) {

        if (rechargeRecord.getPayTime() == null)return false;
        if (rechargeRecord.getAmount() == null) return false;
        if (StringUtils.isBlank(rechargeRecord.getPayCode())) return false;
        if (rechargeRecord.getPayType() == null) return false;
        return true;
    }
}
